<template>
  <div class="delivery-home">
    <!-- 顶部欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <div class="welcome-left">
          <h1 class="welcome-title">欢迎回来，配送员</h1>
          <p class="welcome-subtitle">今天是美好的一天，让我们开始配送工作吧！</p>
          <div class="welcome-time">{{ currentTime }}</div>
        </div>
        <div class="welcome-right">
          <div class="status-indicator" :class="{ online: isOnline }">
            <div class="status-dot"></div>
            <span>{{ isOnline ? '在线' : '离线' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息通知和天气模块 -->
    <div class="info-modules">
      <!-- 消息通知模块 -->
      <div class="notification-module">
        <div class="module-header">
          <h3>
            <el-icon><Bell /></el-icon>
            消息通知
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="notification-badge" />
          </h3>
          <el-button type="primary" link @click="handleMarkAllAsRead" :disabled="unreadCount === 0">
            全部已读
          </el-button>
        </div>
        <div class="notification-list" v-if="!loadingNotifications">
          <div 
            v-for="notification in notifications" 
            :key="notification.id"
            class="notification-item"
            :class="{ unread: !notification.isRead }"
            @click="handleMarkAsRead(notification.id)"
          >
            <div class="notification-title">
              <span v-if="!notification.isRead" style="color:#409EFF;font-weight:bold;">●</span>
              {{ notification.title }}
            </div>
            <div class="notification-message">{{ notification.message }}</div>
            <div class="notification-time">{{ notification.timeAgo }}</div>
            <div class="notification-status" v-if="!notification.isRead">
              <div class="unread-dot"></div>
            </div>
          </div>
          <el-empty v-if="notifications.length === 0" description="暂无通知" />
        </div>
        <div v-else class="notification-loading">
          <el-icon class="is-loading" :size="20"><Loading /></el-icon>
          <span>正在加载通知...</span>
        </div>
      </div>

      <!-- 天气模块 -->
      <div class="weather-module">
        <div class="module-header">
          <h3>
            <el-icon><Sunny /></el-icon>
            当前天气
          </h3>
          <div class="weather-actions">
            <el-button type="primary" link @click="refreshLocation">
              <el-icon><Location /></el-icon>
              重新定位
            </el-button>
            <el-button type="primary" link @click="refreshWeather">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        <div class="weather-content" v-if="weatherData">
          <div class="weather-main">
            <div class="weather-icon">
              <el-icon size="48" :color="weatherData.temp > 20 ? '#ff6b35' : '#409eff'">
                <component :is="getWeatherIcon(weatherData.weather)" />
              </el-icon>
            </div>
            <div class="weather-info">
              <div class="temperature">{{ weatherData.temp }}°C</div>
              <div class="weather-desc">{{ weatherData.weather }}</div>
              <div class="location">
                <el-icon><Location /></el-icon>
                {{ weatherData.city }}
              </div>
              <div class="location-coords" v-if="currentPosition">
                <small>坐标: {{ currentPosition.latitude.toFixed(4) }}, {{ currentPosition.longitude.toFixed(4) }}</small>
              </div>
            </div>
          </div>
          <div class="weather-details">
            <div class="detail-item">
              <span class="detail-label">湿度</span>
              <span class="detail-value">{{ weatherData.humidity }}%</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">风力</span>
              <span class="detail-value">{{ weatherData.windSpeed }} 级</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">风向</span>
              <span class="detail-value">{{ weatherData.windDirection }}</span>
            </div>
          </div>
        </div>
        <div class="weather-loading" v-else>
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>正在获取天气信息...</span>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card pending">
        <div class="stat-icon">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ todayTasks.pending }}</div>
          <div class="stat-label">待配送</div>
        </div>
      </div>
      
      <div class="stat-card delivering">
        <div class="stat-icon">
          <el-icon><Van /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ todayTasks.delivering }}</div>
          <div class="stat-label">配送中</div>
        </div>
      </div>
      
      <div class="stat-card completed">
        <div class="stat-icon">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ todayTasks.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </div>
      
      <div class="stat-card sum">
        <div class="stat-icon">
          <el-icon><List /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ todayTasks.sum }}</div>
          <div class="stat-label">任务包总数</div>
        </div>
      </div>
    </div>

    <!-- 主要功能区 -->
    <div class="main-content">
      <div class="content-left">
        <!-- 当前状态卡片 -->
        <div class="status-card">
          <div class="card-header">
            <h3>当前状态</h3>
            <el-switch
              v-model="isOnline"
              :active-text="isOnline ? '在线' : '离线'"
              active-color="#10b981"
              @change="handleStatusChange"
            />
          </div>
          <div class="status-body">
            <div class="status-display">
              <el-tag :type="statusType" size="large" class="status-tag">
                <el-icon><component :is="statusIcon" /></el-icon>
                {{ statusText }}
              </el-tag>
            </div>
            <div class="status-info">
              <div class="info-item">
                <span class="info-label">工作时长：</span>
                <span class="info-value">{{ workHours }}小时</span>
              </div>
              <div class="info-item">
                <span class="info-label">配送距离：</span>
                <span class="info-value">{{ totalDistance }}公里</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 位置信息卡片 -->
        <div class="location-card">
          <div class="card-header">
            <h3>当前位置</h3>
            <el-button type="primary" size="small" @click="updateLocation">
              <el-icon><Location /></el-icon>
              更新位置
            </el-button>
          </div>
          <div class="location-body">
            <div class="location-display">
              <el-icon><LocationFilled /></el-icon>
              <span>{{ currentLocation || '正在获取位置...' }}</span>
            </div>
            <div class="location-actions">
              <el-button type="success" size="small" @click="startNavigation">
                <el-icon><MapLocation /></el-icon>
                开始导航
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="content-right">
        <!-- 待接单任务包 -->
        <div class="tasks-card">
          <div class="card-header">
            <h3>待接单任务包</h3>
            <el-button type="primary" link @click="$router.push('/delivery/tasks')">
              查看全部
              <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <div class="tasks-list">
            <div 
              v-for="taskPackage in pagedPendingTaskPackages" 
              :key="taskPackage.packageId"
              class="task-package-item"
            >
              <div class="package-header">
                <div class="package-info">
                  <span class="package-id">{{ taskPackage.packageId }}</span>
                  <el-tag size="small" :type="taskPackage.priority === '紧急' ? 'danger' : 'warning'">
                    {{ taskPackage.priority || '普通' }}
                  </el-tag>
                </div>
                <div class="package-stats">
                  <span class="order-count">{{ taskPackage.orderCount }}个订单</span>
                  <span class="total-reward">¥{{ taskPackage.totalReward }}</span>
                </div>
              </div>
              
              <div class="package-details">
                <div class="delivery-area">
                  <el-icon><Location /></el-icon>
                  <span>{{ taskPackage.deliveryArea || '地址未提供' }}</span>
                </div>
                <div class="delivery-time">
                  <el-icon><Clock /></el-icon>
                  <span>{{ taskPackage.formattedDeliveryTime }}</span>
                </div>
                <div class="estimated-distance">
                  <el-icon><MapLocation /></el-icon>
                  <span>预计{{ taskPackage.estimatedDistance }}公里</span>
                </div>
              </div>
              
              <div class="package-orders">
                <div class="orders-preview">
                  <span class="preview-label">包含订单：</span>
                  <div class="order-tags">
                    <el-tag 
                      v-for="orderNumber in (taskPackage.orders || []).slice(0, 3)" 
                      :key="orderNumber"
                      size="small" 
                      type="info"
                    >
                      {{ orderNumber }}
                    </el-tag>
                    <el-tag v-if="(taskPackage.orders || []).length > 3" size="small" type="info">
                      +{{ (taskPackage.orders || []).length - 3 }}
                    </el-tag>
                  </div>
                </div>
              </div>
              
              <div class="package-actions">
                <el-button type="primary" size="small" @click="handleAcceptTaskPackage(taskPackage)">
                  <el-icon><Check /></el-icon>
                  接单
                </el-button>
                <el-button size="small" @click="viewTaskPackageDetail(taskPackage)">
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
              </div>
            </div>
            <el-pagination
              v-if="totalPending > pendingPageSize"
              small
              layout="prev, pager, next"
              :total="totalPending"
              :page-size="pendingPageSize"
              :current-page="pendingPage"
              @current-change="handlePendingPageChange"
              style="margin-top: 10px; text-align: right;"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <div class="action-item" @click="$router.push('/delivery/tasks')">
        <div class="action-icon">
          <el-icon><List /></el-icon>
        </div>
        <span>任务管理</span>
      </div>
      <div class="action-item" @click="$router.push('/delivery/routes/plan')">
        <div class="action-icon">
          <el-icon><MapLocation /></el-icon>
        </div>
        <span>路线规划</span>
      </div>
      <div class="action-item" @click="$router.push('/delivery/stats/personal')">
        <div class="action-icon">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <span>数据统计</span>
      </div>
      <div class="action-item" @click="$router.push('/delivery/profile')">
        <div class="action-icon">
          <el-icon><User /></el-icon>
        </div>
        <span>个人中心</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDeliveryNotifications, getPendingTaskPackages, getTaskPackages, acceptTaskPackage, getTaskPackageStats, markNotificationAsRead, markAllNotificationsAsRead } from '@/assets/delivery.js';
import { getWeatherDataByAdcode } from '@/services/weatherService'
import { getAddressFromCoords } from '@/services/geocodingService'
import {
  Clock,
  Van,
  CircleCheck,
  Money,
  TrendCharts,
  Location,
  LocationFilled,
  MapLocation,
  ArrowRight,
  Check,
  View,
  List,
  User,
  Bell,
  Sunny,
  Refresh,
  Loading,
  Cloudy,
  Moon,
  Umbrella,
  Warning,
  CircleClose,
  GobletSquare,
  DataAnalysis,
  Promotion,
  MessageBox,
  Close
} from '@element-plus/icons-vue'
import {findAllTaskGroup} from "@/assets/delivery.js";
import {useUserStore} from "@/pinia/index.js";
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

const router = useRouter()

// 在线状态
const isOnline = ref(true)

// 配送员状态
const deliverymanStatus = ref(0) // 0-空闲 1-忙碌 2-离线

// 消息通知列表，这个数组将直接在页面上显示
const notifications = ref([])
const loadingNotifications = ref(true)

const fetchNotifications = async () => {
  loadingNotifications.value = true
  try {
    const response = await getDeliveryNotifications()
    if (response.status === 200 && response.data && response.data.data) {
      // 按时间倒序
      const sortedData = response.data.data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      notifications.value = sortedData.map(item => ({
        id: item.id,
        type: item.type,
        title: item.title,
        message: item.message,
        isRead: item.isRead,
        timeAgo: formatDistanceToNow(new Date(item.createdAt), { addSuffix: true, locale: zhCN })
      }))
    } else {
      notifications.value = []
    }
  } catch (e) {
    notifications.value = []
  } finally {
    loadingNotifications.value = false
  }
}

const unreadCount = computed(() => notifications.value.filter(n => !n.isRead).length)

const handleMarkAsRead = async (id) => {
  const msg = notifications.value.find(n => n.id === id)
  if (msg && !msg.isRead) {
    await markNotificationAsRead(id)
    msg.isRead = true
  }
}

const handleMarkAllAsRead = async () => {
  await markAllNotificationsAsRead()
  notifications.value.forEach(n => n.isRead = true)
}

// 天气相关
const weatherData = ref(null)
const currentPosition = ref(null)

// 当前时间
const currentTime = ref('')
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 状态相关
const statusType = computed(() => {
  const types = {
    0: 'success',
    1: 'warning',
    2: 'info'
  }
  return types[deliverymanStatus.value] || 'info'
})

const statusText = computed(() => {
  const texts = {
    0: '空闲',
    1: '忙碌',
    2: '离线'
  }
  return texts[deliverymanStatus.value] || '未知状态'
})

const statusIcon = computed(() => {
  const icons = {
    0: 'Sunny',
    1: 'Loading',
    2: 'Moon'
  }
  return icons[deliverymanStatus.value] || 'Sunny'
})

// 今日任务统计
const todayTasks = ref({
  pending: 0,
  delivering: 0,
  completed: 0,
  cancelled: 0,
  sum: 0
})
const userStore = useUserStore();
//queryPage
const queryPage = ref({
  pageNum: 1,
  pageSize: 10,
  deliveryId: userStore.getUserId
})
//今日任务统计
const fetchTodayTaskStats = async () => {
  try {
    const res = await getTaskPackageStats();
    if (res.data && res.data.data) {
      todayTasks.value.pending = res.data.data.pending || 0;
      todayTasks.value.delivering = res.data.data.delivering || 0;
      todayTasks.value.completed = res.data.data.completed || 0;
      todayTasks.value.cancelled = res.data.data.cancelled || 0;
      todayTasks.value.sum =
        (todayTasks.value.pending || 0) +
        (todayTasks.value.delivering || 0) +
        (todayTasks.value.completed || 0) +
        (todayTasks.value.cancelled || 0);
    }
  } catch (error) {
    console.error('获取任务统计失败:', error);
  }
};
fetchTodayTaskStats()
// 今日收入
const todayEarnings = ref(156.80)

// 工作时长和距离
const workHours = ref(6.5)
const totalDistance = ref(45.2)

// 当前位置
const currentLocation = ref('北京市朝阳区建国路88号')

// 待接单任务包 (现在是空的，将由API填充)
const pendingTaskPackages = ref([]);

// 首页待接单分页
const pendingPage = ref(1)
const pendingPageSize = 2

const pagedPendingTaskPackages = computed(() => {
  const start = (pendingPage.value - 1) * pendingPageSize
  return pendingTaskPackages.value.slice(start, start + pendingPageSize)
})

const totalPending = computed(() => pendingTaskPackages.value.length)

const handlePendingPageChange = (page) => {
  pendingPage.value = page
}

// 获取待接单任务包数据（只查 status: 'pending'）
const fetchPendingTaskPackages = () => {
  const queryParams = {
    page: 1,
    size: 10, // 展示前10个
    status: "pending"
  };
  getTaskPackages(queryParams)
    .then(response => {
      if (response.data && response.data.data && Array.isArray(response.data.data.records)) {
        pendingTaskPackages.value = response.data.data.records.map(pkg => ({
          ...pkg,
          orders: Array.isArray(pkg.orders) ? pkg.orders : []
        }));
      } else {
        pendingTaskPackages.value = [];
      }
    })
    .catch(error => {
      pendingTaskPackages.value = [];
      ElMessage.error('获取待接单任务包失败');
    });
};

// 只统计待配送任务包数量
const fetchPendingTaskCount = async () => {
  const queryParams = {
    page: 1,
    size: 1,
    status: "pending"
  };
  try {
    const response = await getTaskPackages(queryParams);
    if (response.data && response.data.data) {
      todayTasks.value.pending = response.data.data.total || 0;    } else {
      todayTasks.value.pending = 0;
    }
  } catch (error) {
    todayTasks.value.pending = 0;
    ElMessage.error('获取待配送任务数量失败');
  }
};

// 定时器
let timeInterval = null

// 处理状态变更
const handleStatusChange = (val) => {
  deliverymanStatus.value = val ? 0 : 2
  ElMessage.success(val ? '已上线' : '已离线')
}

// 更新位置
const updateLocation = () => {
  refreshLocation();
}

// 开始导航
const startNavigation = () => {
  ElMessage.info('正在启动导航...')
}

// 接受任务包
const handleAcceptTaskPackage = async (taskPackage) => {
  try {
    const res = await acceptTaskPackage(taskPackage.packageId);
    if (res.data && res.data.code === 200) {
      ElMessage.success(`接单成功：${taskPackage.packageId}`);
      // 刷新待接单任务包和待配送数量
      fetchPendingTaskPackages();
      fetchPendingTaskCount();
    } else {
      ElMessage.error(res.data.message || '接单失败');
    }
  } catch (e) {
    ElMessage.error('接单失败');
  }
};

// 查看任务包详情
const viewTaskPackageDetail = (taskPackage) => {
  router.push(`/delivery/tasks/${taskPackage.packageId}`)
}

// 天气相关方法
const getWeatherIcon = (weather) => {
  const iconMap = {
    '晴': 'Sunny',
    '多云': 'Cloudy',
    '阴': 'Moon',
    '雨': 'Umbrella',
    '雪': 'Cloudy',
    '雾': 'Cloudy'
  }
  return iconMap[weather] || 'Sunny'
}

const getCurrentPosition = () => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器不支持地理定位'))
      return
    }
    
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        currentPosition.value = { latitude, longitude }
        console.log('定位成功:', { latitude, longitude })
        resolve({ latitude, longitude })
      },
      (error) => {
        console.error('获取位置失败:', error)
        // 使用保定市默认位置
        const baodingPosition = { latitude: 38.8671, longitude: 115.4825 }
        currentPosition.value = baodingPosition
        console.log('使用保定市默认位置:', baodingPosition)
        resolve(baodingPosition)
      },
      {
        enableHighAccuracy: true,
        timeout: 15000, // 增加超时时间
        maximumAge: 300000 // 5分钟内的缓存位置
      }
    )
  })
}

const fetchWeatherAndLocation = async () => {
  weatherData.value = null; // 进入加载状态
  try {
    const position = await getCurrentPosition();
    const locationInfo = await getAddressFromCoords(position.latitude, position.longitude);

    if (locationInfo && locationInfo.adcode) {
      currentLocation.value = locationInfo.address; // 更新为详细地址
      const weatherInfo = await getWeatherDataByAdcode(locationInfo.adcode);
      if (weatherInfo) {
        weatherData.value = { ...weatherInfo };
        ElMessage.success('天气和位置已更新');
      } else {
        ElMessage.error('获取天气信息失败');
      }
    } else {
      ElMessage.error('获取位置信息失败');
    }
  } catch (error) {
    console.error('更新天气和位置失败:', error);
    ElMessage.error('更新天气和位置失败');
  }
};

const refreshWeather = async () => {
  await fetchWeatherAndLocation();
}

const refreshLocation = async () => {
  await fetchWeatherAndLocation();
}

onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  
  // 初始化通知数据
  fetchNotifications()
  
  // 初始化待接单任务包数据
  fetchPendingTaskPackages()
  
  // 初始化天气信息
  fetchWeatherAndLocation()
  
  // 只统计待配送任务包数量
  fetchPendingTaskCount()
  
  // 获取今日任务统计
  fetchTodayTaskStats()
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style scoped>
.delivery-home {
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  min-height: 100vh;
}

/* 欢迎区域 */
.welcome-section {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-radius: 20px;
  padding: 32px;
  margin-bottom: 24px;
  color: white;
  box-shadow: 0 10px 25px rgba(16, 185, 129, 0.3);
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.welcome-subtitle {
  font-size: 16px;
  margin: 0 0 16px 0;
  opacity: 0.9;
}

.welcome-time {
  font-size: 14px;
  opacity: 0.8;
  font-family: 'Courier New', monospace;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(10px);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ef4444;
  animation: pulse 2s infinite;
}

.status-indicator.online .status-dot {
  background: #10b981;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 消息通知和天气模块 */
.info-modules {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.notification-module,
.weather-module {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.notification-module:hover,
.weather-module:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.module-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

/* 消息通知模块样式 */
.notification-badge {
  margin-left: 8px;
}

.notification-list {
  max-height: 250px;
  overflow-y: auto;
  padding-right: 10px;
  margin-right: -10px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.notification-item:hover {
  background: #f8fafc;
  border-color: #e2e8f0;
}

.notification-item.unread {
  background: #f0f9ff;
  border-color: #0ea5e9;
}

.notification-icon {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f1f5f9;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
  line-height: 1.4;
}

.notification-time {
  font-size: 11px;
  color: #9ca3af;
}

.notification-status {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.unread-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ef4444;
}

/* 天气模块样式 */
.weather-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.weather-main {
  display: flex;
  align-items: center;
  gap: 20px;
}

.weather-icon {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.weather-info {
  flex: 1;
}

.temperature {
  font-size: 36px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 8px;
}

.weather-desc {
  font-size: 16px;
  color: #6b7280;
  margin-bottom: 8px;
}

.location {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #9ca3af;
}

.location-coords {
  margin-top: 4px;
  font-size: 11px;
  color: #6b7280;
  opacity: 0.8;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  color: #6b7280;
}

.detail-value {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.weather-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 40px 20px;
  color: #6b7280;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--card-color), var(--card-color-light));
}

.stat-card.pending {
  --card-color: #3b82f6;
  --card-color-light: #60a5fa;
}

.stat-card.delivering {
  --card-color: #f59e0b;
  --card-color-light: #fbbf24;
}

.stat-card.completed {
  --card-color: #10b981;
  --card-color-light: #34d399;
}

.stat-card.sum {
  background: linear-gradient(135deg, #6366f1, #a5b4fc);
  color: #fff;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: linear-gradient(135deg, var(--card-color), var(--card-color-light));
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #10b981;
  font-weight: 500;
}

/* 主要内容区 */
.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.content-left {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-right {
  display: flex;
  flex-direction: column;
}

/* 卡片通用样式 */
.status-card,
.location-card,
.tasks-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.status-card:hover,
.location-card:hover,
.tasks-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

/* 状态卡片 */
.status-body {
  text-align: center;
}

.status-display {
  margin-bottom: 20px;
}

.status-tag {
  font-size: 16px;
  padding: 8px 16px;
  border-radius: 20px;
}

.status-info {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.info-label {
  font-size: 12px;
  color: #6b7280;
}

.info-value {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

/* 位置卡片 */
.location-body {
  text-align: center;
}

.location-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 12px;
  color: #374151;
}

.location-actions {
  display: flex;
  justify-content: center;
}

/* 任务卡片 */
.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-package-item {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.task-package-item:hover {
  background: #f1f5f9;
  transform: translateX(4px);
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.package-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.package-id {
  font-weight: 600;
  color: #1f2937;
}

.package-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.order-count {
  font-size: 14px;
  color: #6b7280;
}

.total-reward {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.package-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.delivery-area,
.delivery-time,
.estimated-distance {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #6b7280;
}

.package-orders {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background: #f1f5f9;
  border-radius: 8px;
}

.orders-preview {
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.order-tags {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
}

.package-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
}

/* 快捷操作 */
.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.action-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #10b981, #34d399);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.action-item span {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .welcome-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
}

@media (max-width: 768px) {
  .delivery-home {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .welcome-title {
    font-size: 24px;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

.weather-actions {
  display: flex;
  gap: 8px;
}

.notification-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #909399;
}
</style> 